/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.huawei.rpc.server.register;

import com.alibaba.fastjson.JSON;
import com.huawei.rpc.common.constants.CommonConstant;
import com.huawei.rpc.common.info.ServiceInfo;
import com.huawei.rpc.common.serializer.ZookeeperSerializer;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.List;


/**
 * @Author Lijl
 * @ClassName ZookeeperExportServiceRegister
 * @Description Zookeeper服务注册，提供服务注册、服务暴露
 * @Date 2022/2/15 15:26
 * @Version 1.0
 */
public class ZookeeperExportServiceRegister extends DefaultServiceRegister {
    /**
     * zk客户端
     */
    private ZkClient client;
    public ZookeeperExportServiceRegister(String zkAddress, int port, String protocol){
        this.client = new ZkClient(zkAddress);
        this.client.setZkSerializer(new ZookeeperSerializer());
        this.port = port;
        this.protocol = protocol;
    }

    /**
     * @Author lijl
     * @MethodName register
     * @Description 缓存服务持有对象，并注册服务
     * @Date 15:38 2022/2/15
     * @Version 1.0
     * @param soList 服务持有者集合
     * @return: void
    **/
    @Override
    public void register(List<ServiceObject> soList) throws Exception {
        super.register(soList);
        for (ServiceObject so : soList) {
            ServiceInfo serviceInfo = new ServiceInfo();
            String host = InetAddress.getLocalHost().getHostAddress();
            String address = host + ":" + port;
            serviceInfo.setAddress(address);
            serviceInfo.setName(so.getName());
            serviceInfo.setProtocol(protocol);
            this.exportService(serviceInfo);
        }
    }

    /**
     * @Author lijl
     * @MethodName exportService
     * @Description 暴露服务
     * @Date 15:38 2022/2/15
     * @Version 1.0
     * @param serviceInfo 需要暴露的服务信息
     * @return: void
    **/
    private void exportService(ServiceInfo serviceInfo) {
        String serviceName = serviceInfo.getName();
        String uri = JSON.toJSONString(serviceInfo);

        try {
            uri = URLEncoder.encode(uri, CommonConstant.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String servicePath = CommonConstant.ZK_SERVICE_PATH + CommonConstant.PATH_DELIMITER + serviceName + CommonConstant.PATH_DELIMITER + "service";
        if (!client.exists(servicePath)){
            client.createPersistent(servicePath,true);
        }
        String uriPath = servicePath + CommonConstant.PATH_DELIMITER + uri;
        if (client.exists(uriPath)){
            client.delete(uriPath);
        }
        client.createEphemeral(uriPath);
    }
}
